You can inject js script into the document head dynamically like this :
const basicScript = document.createElement('script');
basicScript.type = 'text/javascript';
basicScript.innerHTML = `
console.log('This is a basic script injection.');
`;
document.head.appendChild(basicScript); // append script into head tag
// OR
document.body.appendChild(basicScript); // append script into body tag
I followed this approach to dynamically inject JavaScript scripts into the and <head> tags via an AJAX call in a cached Laravel application.<body>
This method allows you to dynamically inject and execute a basic script into the document head or body.
You Might Also Like
Dynamically Update Attribute Values
To change the attributes of multiple elements based on user input or other dynamic conditions. Use ~...
Efficiently Append Multiple Elements
Appending multiple elements to the DOM can be inefficient if done individually. Use a document frag...